package com.cloudptt.wp.ui.dlg;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.cloudptt.api.product.ISuperCallOperator;
import com.cloudptt.api.product.Product;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.func.call.CallConst;
import com.cloudptt.api.product.func.call.single.LaunchCallInfo;
import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.SysApplication;
import com.cloudptt.wp.ui.message.GroupMemberActivity;
import com.cloudptt.wp.ui.message.SessionActivity;
import com.mcptt.db.model.AddrInfo;

public class CallInfoDlg extends AlertDialog implements View.OnClickListener, DialogInterface.OnKeyListener {
    private Context context = null;
    private String curCallKey = null;
    private AddrInfo peerAddrInfo = null;
    private LaunchCallInfo info = null;
    private boolean canClose = false;
    private Product product = null;

    public CallInfoDlg(@NonNull Context context, AddrInfo peerAddrInfo, LaunchCallInfo info, boolean canClose) {
        super(context, R.style.FullWidthDialogTheme); // 使用自定义样式
        this.context = context;
        this.peerAddrInfo = peerAddrInfo;
        this.setOnKeyListener(this);
        if(info != null) {
            this.curCallKey = info.getCallKey();
        }
        this.info = info;
        this.canClose = canClose;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.debug(this.getClass(), "onCreate");
        setContentView(R.layout.dialog_call_info); // 绑定自定义布局
        // 初始化控件和事件
        ImageView listView  = (ImageView)findViewById(R.id.faceIv);
        TextView nameTv  = (TextView)findViewById(R.id.nameTv);
        if(peerAddrInfo != null)
        {
            String dscp = peerAddrInfo.getDscp();
            if(info.isEmergency())
            {
                dscp = context.getString(R.string.title_emergency) + dscp;
                nameTv.setTextColor(Color.RED);
            }
            nameTv.setText(dscp);
        }
        ImageView memberIv  = (ImageView)findViewById(R.id.memberIv);
        memberIv.setOnClickListener(this);
        ImageView rejectIv  = (ImageView)findViewById(R.id.rejectIv);
        rejectIv.setOnClickListener(this);
        ImageView acceptIv  = (ImageView)findViewById(R.id.acceptIv);
        if(info.isHasVideo())
        {
            acceptIv.setImageResource(R.drawable.bg_accept_video);
        }
        TextView tipTv  = (TextView)findViewById(R.id.tipTv);
        int callState = info.getCallState();
        if(CallConst.CallState_Activite == callState)
        {
            String str =getCallTypeDesc(info.getCallType(), info.isHasVideo());
            String tipStr = context.getString(R.string.single_call_conncted, str);
            tipTv.setText(tipStr);
            memberIv.setVisibility(View.VISIBLE);
            acceptIv.setVisibility(View.GONE);
            if(info.isEmergency()
                && !info.isMoCall())
            {
                rejectIv.setVisibility(View.GONE);
            }
        }
        else
        {
            if (info.isMoCall()) {
                tipTv.setText(R.string.single_call_conncting_mo);
            } else {
                String str = getCallTypeDesc(info.getCallType(), info.isHasVideo());
                String tipStr = context.getString(R.string.single_call_conncting_mt, str);
                tipTv.setText(tipStr);
            }
        }

        acceptIv.setOnClickListener(this);

        setCanceledOnTouchOutside(canClose);
        setCancelable(true);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        Window window = getWindow();
        if (window != null) {
//			window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = WindowManager.LayoutParams.MATCH_PARENT;  // 宽度充满屏幕
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;             // 高度为屏幕一半
            DisplayMetrics metrics = new DisplayMetrics();
            window.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            params.y = (int) (metrics.heightPixels * 0.1);
            window.setAttributes(params);

            window.setGravity(Gravity.TOP); // 可选：设置对话框位置（如底部）
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.debug(this.getClass(), "onStart");
    }

    @Override
    public void show() {
        if(!isShowing()) {
            super.show();
        }
        Log.debug(this.getClass(), "show");
    }

    @Override
    public void cancel() {
        super.cancel();
        Log.debug(this.getClass(), "cancel");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.debug(this.getClass(), "onStop");
    }

    @Override
    public void dismiss() {
        super.dismiss();
        Log.debug(this.getClass(), "dismiss");
    }

    private String getCallTypeDesc(int type, boolean hasVideo)
    {
        if(type == CallAttr.CallType_Pull_One_To_One
                || type == CallAttr.CallType_Pull_One_To_Svr)
        {
            return context.getString(R.string.single_call_video_pull);
        }
        else if(type == CallAttr.CallType_Push_One_To_One
                || type == CallAttr.CallType_Push_One_To_Svr)
        {
            return context.getString(R.string.single_call_video_push);
        }
        else
        {
            if(CallAttr.isGroupCall(type))
            {
                if(!hasVideo)
                {
                    return context.getString(R.string.group_call_voice);
                }
                else
                {
                    return context.getString(R.string.group_call_video);
                }
            }
            else
            {
                if (!hasVideo)
                {
                    return context.getString(R.string.single_call_voice);
                }
                else
                {
                    return context.getString(R.string.single_call_video);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.memberIv:
                Log.debug(this.getClass(), "memberIv");
                this.dismiss();
                Intent intent = new Intent();
                intent.setClass(context, GroupMemberActivity.class);
                intent.getBooleanExtra(GroupMemberActivity.KEY_SHOW,false);
                intent.putExtra(SessionActivity.KEY,peerAddrInfo);
                //		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                context.startActivity(intent);
                break;
            case R.id.acceptIv:
                Log.debug(this.getClass(), "acceptIv");
                doUserAction(CallConst.BtnAction_Accept,"");
                break;
            case R.id.rejectIv:
                Log.debug(this.getClass(), "hangupIv");
                int callState = info.getCallState();
                if(CallConst.CallState_Activite == callState)
                {
                    doUserAction(CallConst.BtnAction_Hangup,"");
                }
                else
                {
                    doUserAction(CallConst.BtnAction_Reject,"");
                }

                break;
            default:
                break;
        }
    }



    public void doUserAction(int btnAction,String infoStr) {
        if (product == null) {
            SysApplication app = ((SysApplication) context.getApplicationContext());
            product = app.getProduct();
        }
        if (product != null) {
            ISuperCallOperator op = product.getSuperCallOperator();
            op.doUserAction(curCallKey, btnAction,infoStr);
        }
    }

    @Override
    public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK ||
                keyCode == KeyEvent.KEYCODE_SEARCH) {
            return true; // 拦截按键事件
        }
        return false;
    }

    public AddrInfo getPeerAddrInfo() {
        return peerAddrInfo;
    }

    public LaunchCallInfo getInfo() {
        return info;
    }
}
